package cn.com.open.ms.ecgpaasdatarest.log;

import cn.com.open.ms.ecgpaasdatarest.common.Constant;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * 日志发送类
 *
 * @author guxuyang
 */
@Component
public class ServiceLogSender {

    private static final Logger Log= LoggerFactory.getLogger(ServiceLogSender.class);

    @Autowired
    private RestTemplate restTemplate;
    @Value("${base.service.log.url}")
    private String baseServiceLogUrl;

    /**
     * 记录接口调用日志
     * @param apiServiceLog log model
     */
    void sendServiceLog(JSONObject apiServiceLog) {
        MultiValueMap<String, Object> logMap = new LinkedMultiValueMap<>();
        logMap.add("tag", Constant.LOG_DB_NAME);
        logMap.add("logData", JSONObject.toJSONString(apiServiceLog));
        sendLog(logMap);
    }

    @Async
    public void sendLog(MultiValueMap<String, Object> logMap) {
        try {
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8");
            headers.setContentType(type);
            HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(logMap, headers);
            ResponseEntity<String> result = restTemplate.exchange(baseServiceLogUrl, HttpMethod.POST, entity, String.class);
            String str = new String(result.getBody().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            Log.info(str);
        } catch (Exception e) {
            Log.error("调用基础服务日志接口异常", e);
        }
    }

}
